
import socket


class WebServer(object):
    """
        将服务器的初始化和开启封装为类
    """
    def __init__(self):
        server_sc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        server_sc.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
        server_sc.bind(("0.0.0.0", 8080))

        server_sc.listen(128)

        self.server_sc = server_sc

    def start(self):
        while True:
            client_sc, ip_port = self.server_sc.accept()
            print("%s客户端已连接" % str(ip_port))

            self.handler(client_sc)

    def handler(self, client_sc):
        request_data = client_sc.recv(1024)
        request_text = request_data.decode()

        loc = request_text.find("\r\n")

        request_line = request_text[:loc]
        request_line_list = request_line.split(" ")
        file_name = request_line_list[1]
        # print(file_path)
        file_path = "D:\\python-workstation\\study_dir\\002_http_study"

        response_line = "HTTP/1.1 200 OK\r\n"
        response_header = "Server:Python20WS/0.1\r\n"
        response_blank = "\r\n"
        with open(file_path + file_name, "r") as file:
            file_data = file.read()

        response_body = file_data

        response_data = response_line + response_header + response_blank + response_body

        client_sc.send(response_data.encode())
        client_sc.close()


if __name__ == '__main__':
    web = WebServer()
    web.start()
